<?php

class Core_Router
{
	protected static $_instance = null;

	protected function  __construct()
	{}


	public static function instance()
	{
		if (null === self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	public function run($route)
	{
		$request = Core_Request::instance();
		$request->route = $route;
		$parts = explode('/', $route);

		if (count($parts) === 1) {
			$request->controller = empty ($parts[0]) ? 'index' : $parts[0];
			$request->action = 'index';
		} else {
			$request->controller = array_shift($parts);
			$request->action = array_shift($parts);
		}
		unset($_GET['route']);

		foreach ($_GET as $key => $value){
			$request -> params[$key] = is_null($value) ? '' :$value;
		}

		//TODO remove next row
		file_put_contents("1.1", "\t".serialize($request -> params).
		"\n\trequest->action = ".$request->action."\n\t".
		"request->controller = ".$request->controller."\n",FILE_APPEND);

		if (!$this->get_controllers($request->controller)) {
			$request->controller = 'index';
			$request->action = 'index';
		}


		$request->controller = 'App_Controllers_' . $request->controller;
		$controller = new $request->controller;
		call_user_func(array($controller,$request->action),$request);

		//TODO remove next row
		file_put_contents("1.1", "\t\t".serialize($request -> params).
		"\n\t\trequest->action = ".$request->action."\n".
		"\t\trequest->controller = ".$request->controller."\n",FILE_APPEND);
	}

	public function get_controllers($controller)
	{
		try {
			$controller = 'App_Controllers_'  . $controller ;
			@Core_Loader::load_class($controller,APP . 'Controllers' . DS);
			//new $controller;
			return true;
		} catch (Exception $exc) {
			//echo $exc->getMessage();
			return false;
		}

	}


}

?>